package com.itxiaoxiong.chat.service.impl;

import com.itxiaoxiong.chat.mapper.LoginMapper;
import com.itxiaoxiong.chat.mapper.UserMapper;
import com.itxiaoxiong.chat.pojo.User;
import com.itxiaoxiong.chat.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private UserMapper userMapper;

    private Set<String> loggedInUsernames = new HashSet<>();

    @Override
    public User login(User user) {
        if (isUserLoggedIn(user.getUsername())) {
            return null;
        }
        String key = "user:" + user.getUsername();
        log.error(key);
        String password = stringRedisTemplate.opsForValue().get(key);
        log.error(password);
        log.error(user.getPassword());
        if(!password.equals(user.getPassword())){
            log.error("Redis操作错误");
        }else{
            log.error("Redis操作正确");
        }
        User u = loginMapper.login(user);
        if (u!= null) {
            loggedInUsernames.add(user.getUsername());
        }
        return u;
    }

    @Override
    public boolean isUserLoggedIn(String username) {
        return loggedInUsernames.contains(username);
    }

    @Override
    public void outLogin(Integer id) {
        User user = userMapper.listUserName(id);
        if (user!= null) {
            String username = user.getUsername();
            loggedInUsernames.remove(username);
        }
        String idString = String.valueOf(id);
        loginMapper.outLogin(idString);
    }
}
